<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Amenu extends Controller_Abase_Adefaultactions {

    public function action_add() {
        $newObj = ORM::factory($this->request->controller());
        $fields = arr::path($this->params(), 'fields'); // Получаем поля сверху

        foreach ($fields as $key => $item) { // Заполняем значения полей
            $newObj->$key = $this->request->post($key);
        }

		$link = $this->request->post('link');

        if (empty($link)) {
            $q = DB::select('link')->from('pages')->where('id', '=', $this->request->post('page_id'))->as_object()->execute()->current();
            $newObj->link = 'page/'.$q->link;
        	$newObj->page_id = $this->request->post('page_id');
        } else {
        	$newObj->link = $link;
        	$newObj->page_id = 0;
        }

        $newObj->save();
        $this->redirect('administration/'.$this->request->controller().'/'.$this->request->param('page'));
    }

    public function action_edit() {
        $obj = ORM::factory($this->request->controller(), $this->request->param('id'));

        if ($this->request->param('save')) {
            $fields = arr::path($this->params(), 'fields'); // Получаем поля сверху

            foreach ($fields as $key => $item) { // Заполняем новые значения полей
                $obj->$key = $this->request->post($key);
            }

			$link = $this->request->post('link');

	        if (empty($link)) {
                $q = DB::select('link')->from('pages')->where('id', '=', $this->request->post('page_id'))->as_object()->execute()->current();
	        	$obj->link = 'page/'.$q->link;
	        	$obj->page_id = $this->request->post('page_id');
	        } else {
	        	$obj->link = $link;
	        	$obj->page_id = 0;
	        }

            $obj->save();
            $this->redirect('administration/'.$this->request->controller().'/'.$this->request->param('page').'/edit/'.$this->request->param('id'));
        }

        $params = $this->params($obj);
        $this->showDefaultForm($params, $obj, 'edit');
        $this->showPagination(); // Пагинация
        $this->showDefaultList(); // Рендерим список данных и форму редактирования\добавления
    }

}